const Proxy = require('../proxy')

const UserBtb = Proxy.UserBtb

exports.getUserBtbs = async function (data) {
  return UserBtb.find({
    user_name: data.userName
  })
}

exports.getUserBtb = async function (data) {
  return UserBtb.findOne({
    user_name: data.userName,
    type: data.type
  })
}

exports.addPosition = async function (data) {
  const userBtb = await UserBtb.findOne({
    user_name: data.userName,
    type: data.type
  })
  if (userBtb) {
    let positionRecord = userBtb.position_record
    positionRecord.push({
      shares: data.shares
    })
    return UserBtb.update({
      user_name: data.userName,
      type: data.type
    }, {
      position_record: positionRecord
    })
  } else {
    let positionRecord = []
    positionRecord.push({
      shares: data.shares
    })
    return UserBtb.newAndSave({
      user_name: data.userName,
      type: data.type,
      position_record: positionRecord
    })
  }
}

exports.cutPosition = async function (data) {
  const userBtb = await UserBtb.findOne({
    user_name: data.userName,
    type: data.type
  })
  if (userBtb) {
    let positionRecord = userBtb.position_record
    // 减掉
    let shares = data.shares
    let newRecord = []
    for (let i = 0; i < positionRecord.length; i++) {
      let item = positionRecord[i]
      // 持有的比较多，说明这个没有减掉
      if (item.shares > shares) {
        newRecord.push({
          shares: (item.shares - shares).toFixed(8),
          confirm_date: item.confirm_date
        })
        shares = 0
      } else {
        // 这项被减掉了
        shares = shares - item.shares
      }
    }
    return UserBtb.update({
      user_name: data.userName,
      type: data.type
    }, {
      position_record: positionRecord
    })
  } else {
    let positionRecord = []
    return UserBtb.newAndSave({
      user_name: data.userName,
      type: data.type,
      position_record: positionRecord
    })
  }
}
